<template>
  <div class="page-wrapper">
    <div class="page-header">
      <span class="text-primary font-bold">用户管理</span>
      <el-button type="primary" @click="handleAdd">新增用户</el-button>
    </div>

    <div class="page-content">
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.userName" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="searchForm.nickName" placeholder="请输入昵称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <div class="table-wrapper">
        <el-table :data="tableData" border v-loading="loading">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="id" label="ID" min-width="200" show-overflow-tooltip />
          <el-table-column prop="nickName" label="昵称" min-width="120" show-overflow-tooltip />
          <el-table-column prop="userName" label="用户名" min-width="120" show-overflow-tooltip />
          <el-table-column label="状态" width="80" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                {{ row.status === 1 ? '正常' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="280" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
              <el-button type="warning" link @click="handleResetPassword(row)">重置密码</el-button>
              <el-button type="primary" link @click="handleManageKeys(row)">密钥管理</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="500px"
      destroy-on-close
    >
      <el-form ref="userFormRef" :model="userForm" :rules="userRules" label-width="100px">
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="userForm.nickName" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userForm.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item v-if="dialogType === 'add'" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="userForm.status" placeholder="请选择状态">
            <el-option :value="1" label="正常" />
            <el-option :value="0" label="停用" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="resetPwdDialogVisible"
      title="重置密码"
      width="400px"
      destroy-on-close
    >
      <el-form
        ref="resetPwdFormRef"
        :model="resetPwdForm"
        :rules="resetPwdRules"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="resetPwdForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="resetPwdForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetPwdDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="resetPwdLoading" @click="handleResetPasswordSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 密钥管理对话框 -->
    <el-dialog
      v-model="keyDialogVisible"
      :title="'密钥管理 - ' + currentUserName"
      width="1000px"
      destroy-on-close
    >
      <div class="key-management">
        <div class="key-header" style="margin-bottom: 10px">
          <el-button type="primary" @click="handleAddKey">新增密钥</el-button>
        </div>
        <el-table :data="keyList" border>
          <el-table-column prop="title" label="标题" min-width="120" />
          <el-table-column prop="apiKey" label="API Key" min-width="200" show-overflow-tooltip>
            <template #default="{ row }">
              <div class="api-key-cell">
                <span class="api-key-text">{{ row.apiKey }}</span>
                <el-button
                  class="copy-button"
                  type="primary"
                  link
                  :icon="CopyDocument"
                  @click="copyApiKey(row.apiKey)"
                  title="复制API Key"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column prop="expiresTime" label="过期时间" width="180" />
          <el-table-column label="状态" width="80" align="center">
            <template #default="{ row }">
              <span :class="{ 'status-valid': row.isValid, 'status-invalid': !row.isValid }">
                {{ row.isValid ? '有效' : '已禁用' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template #default="{ row }">
              <el-button
                :type="row.isValid ? 'danger' : 'success'"
                link
                @click="handleToggleKeyStatus(row)"
              >
                {{ row.isValid ? '禁用' : '启用' }}
              </el-button>
              <el-button type="danger" link @click="handleDeleteKey(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="keyDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增密钥对话框 -->
    <el-dialog v-model="addKeyDialogVisible" title="新增密钥" width="500px" destroy-on-close>
      <el-form ref="keyFormRef" :model="keyForm" :rules="keyRules" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="keyForm.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <el-input v-model="keyForm.intro" type="textarea" placeholder="请输入简介" />
        </el-form-item>
        <el-form-item label="过期时间" prop="expiresTime">
          <el-date-picker
            v-model="keyForm.expiresTime"
            type="datetime"
            placeholder="选择过期时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addKeyDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="addKeyLoading" @click="handleAddKeySubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { CopyDocument } from '@element-plus/icons-vue'
import {
  getSystemUserList,
  postSystemUser,
  putSystemUser,
  deleteSystemUserId,
  putSystemUserResetPassword,
  getApiKeyDataList,
  postApiKeyDataCreate,
  putApiKeyDataUpdate,
  deleteApiKeyDataDelete
} from '@/api/system/user'
import type {
  UserVo,
  UserQuery,
  UserForm,
  ResetPasswordForm,
  ApiKeyVo,
  ApiKeyForm
} from '@/types/system/user'

// 搜索表单
const searchForm = reactive<UserQuery>({
  pageNum: 1,
  pageSize: 10,
  userName: undefined,
  nickName: undefined
})

// 表格数据
const tableData = ref<UserVo[]>([])
const loading = ref(false)
const total = ref(0)

// 用户对话框相关
const userDialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const submitLoading = ref(false)
const userFormRef = ref<FormInstance>()
const userForm = reactive<UserForm>({
  id: '',
  nickName: '',
  userName: '',
  password: '',
  status: 1
})

const userRules: any = {
  nickName: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 重置密码对话框相关
const resetPwdDialogVisible = ref(false)
const resetPwdLoading = ref(false)
const resetPwdFormRef = ref<FormInstance>()
const currentUserId = ref('')
const resetPwdForm = reactive<ResetPasswordForm>({
  id: '',
  newPassword: '',
  confirmPassword: ''
})

const resetPwdRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: (error?: Error) => void) => {
        if (value !== resetPwdForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 密钥管理对话框相关
const keyDialogVisible = ref(false)
const currentUserName = ref('')
const keyList = ref<ApiKeyVo[]>([])

// 新增密钥对话框相关
const addKeyDialogVisible = ref(false)
const addKeyLoading = ref(false)
const keyFormRef = ref<FormInstance>()
const keyForm = reactive<ApiKeyForm>({
  title: '',
  intro: '',
  expiresTime: '',
  loginId: ''
})

const keyRules: any = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  expiresTime: [{ required: true, message: '请选择过期时间', trigger: 'change' }]
}

// 加载用户列表
const loadData = async () => {
  loading.value = true
  try {
    const res = await getSystemUserList(searchForm)
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索和重置
const handleSearch = () => {
  searchForm.pageNum = 1
  loadData()
}

const resetSearch = () => {
  searchForm.userName = ''
  searchForm.nickName = ''
  handleSearch()
}

// 新增用户
const handleAdd = () => {
  dialogType.value = 'add'
  userDialogVisible.value = true
  userForm.id = ''
  userForm.nickName = ''
  userForm.userName = ''
  userForm.password = ''
  userForm.status = 1
}

// 编辑用户
const handleEdit = (row: UserVo) => {
  dialogType.value = 'edit'
  userDialogVisible.value = true
  Object.assign(userForm, row)
  userForm.password = '' // 编辑时不显示原密码
}

// 删除用户
const handleDelete = async (row: UserVo) => {
  try {
    ElMessageBox.confirm('确认要删除该用户吗？', '提示', {
      type: 'warning'
    })
    await deleteSystemUserId(row.id)
    ElMessage.success('删除成功')
    await loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  }
}

// 提交用户表单
const handleSubmit = async () => {
  if (!userFormRef.value) return
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (dialogType.value === 'add') {
          await postSystemUser(userForm)
        } else {
          await putSystemUser(userForm)
        }
        ElMessage.success(dialogType.value === 'add' ? '新增成功' : '更新成功')
        userDialogVisible.value = false
        await loadData()
      } catch (error) {
        console.error('保存用户失败:', error)
        ElMessage.error('保存用户失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 重置密码相关
const handleResetPassword = (row: UserVo) => {
  resetPwdDialogVisible.value = true
  currentUserId.value = row.id
  resetPwdForm.id = row.id
  resetPwdForm.newPassword = ''
  resetPwdForm.confirmPassword = ''
}

const handleResetPasswordSubmit = async () => {
  if (!resetPwdFormRef.value) return
  resetPwdFormRef.value.validate(async (valid) => {
    if (valid) {
      resetPwdLoading.value = true
      try {
        resetPwdForm.id = currentUserId.value
        await putSystemUserResetPassword(resetPwdForm)
        ElMessage.success('密码重置成功')
        resetPwdDialogVisible.value = false
      } catch (error) {
        console.error('密码重置失败:', error)
        ElMessage.error('密码重置失败')
      } finally {
        resetPwdLoading.value = false
      }
    }
  })
}

// 密钥管理相关
const handleManageKeys = async (row: UserVo) => {
  keyDialogVisible.value = true
  currentUserId.value = row.id
  currentUserName.value = row.userName
  await loadKeyList()
}

const loadKeyList = async () => {
  try {
    const res = await getApiKeyDataList({ loginId: currentUserId.value })
    keyList.value = res.data
  } catch (error) {
    console.error('获取密钥列表失败:', error)
    ElMessage.error('获取密钥列表失败')
  }
}

const handleAddKey = () => {
  addKeyDialogVisible.value = true
  keyForm.loginId = currentUserId.value
  keyForm.title = ''
  keyForm.intro = ''
  keyForm.expiresTime = ''
}

const handleAddKeySubmit = async () => {
  if (!keyFormRef.value) return
  keyFormRef.value.validate(async (valid) => {
    if (valid) {
      addKeyLoading.value = true
      try {
        await postApiKeyDataCreate(keyForm)
        ElMessage.success('密钥创建成功')
        addKeyDialogVisible.value = false
        await loadKeyList()
      } catch (error) {
        console.error('密钥创建失败:', error)
        ElMessage.error('密钥创建失败')
      } finally {
        addKeyLoading.value = false
      }
    }
  })
}

const handleToggleKeyStatus = async (key: ApiKeyVo) => {
  try {
    ElMessageBox.confirm(
      `确认要${key.isValid ? '禁用' : '启用'}该密钥吗？`,
      '提示',
      {
        type: 'warning'
      }
    )
    key.isValid = !key.isValid
    await putApiKeyDataUpdate(key)
    ElMessage.success(`${key.isValid ? '启用' : '禁用'}成功`)
    await loadKeyList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${key.isValid ? '禁用' : '启用'}失败:`, error)
      ElMessage.error(`${key.isValid ? '禁用' : '启用'}失败`)
    }
  }
}

const handleDeleteKey = async (key: ApiKeyVo) => {
  try {
    ElMessageBox.confirm('确认要删除该密钥吗？', '提示', {
      type: 'warning'
    })
    await deleteApiKeyDataDelete(key.id)
    ElMessage.success('删除成功')
    await loadKeyList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 分页处理
const handleSizeChange = (val: number) => {
  searchForm.pageSize = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  searchForm.pageNum = val
  loadData()
}

// 复制API Key
const copyApiKey = async (apiKey: string) => {
  try {
    await navigator.clipboard.writeText(apiKey)
    ElMessage.success('API Key已复制到剪贴板')
  } catch (err) {
    ElMessage.error('复制失败')
  }
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.status-valid {
  color: #67c23a;
}

.status-invalid {
  color: #f56c6c;
}

.api-key-cell {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.api-key-text {
  flex: 1;
  margin-right: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.copy-button {
  flex-shrink: 0;
}
</style>
